const keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='

function removePaddingChars(input) {
  var lkey = keyStr.indexOf(input.charAt(input.length - 1));
  if (lkey == 64) {
    return input.substring(0, input.length - 1);
  }
  return input;
}

function base64ToBinary(input) {
  var bytes = (input.length / 4) * 3;
  var arrayBuffer = new ArrayBuffer(bytes);
  //get last chars to see if are valid
  input = removePaddingChars(input);
  input = removePaddingChars(input);

  var bytes = parseInt((input.length / 4) * 3, 10);

  var uarray;
  var chr1, chr2, chr3;
  var enc1, enc2, enc3, enc4;
  var i = 0;
  var j = 0;

  if (arrayBuffer)
    uarray = new Uint8Array(arrayBuffer);
  else
    uarray = new Uint8Array(bytes);

  input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

  for (i = 0; i < bytes; i += 3) {
    //get the 3 octects in 4 ascii chars
    enc1 = keyStr.indexOf(input.charAt(j++));
    enc2 = keyStr.indexOf(input.charAt(j++));
    enc3 = keyStr.indexOf(input.charAt(j++));
    enc4 = keyStr.indexOf(input.charAt(j++));

    chr1 = (enc1 << 2) | (enc2 >> 4);
    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
    chr3 = ((enc3 & 3) << 6) | enc4;

    uarray[i] = chr1;
    if (enc3 != 64) uarray[i + 1] = chr2;
    if (enc4 != 64) uarray[i + 2] = chr3;
  }

  return uarray;
}

function binaryToBase64(input) {
  var output = ''
  var chr1, chr2, chr3, enc1, enc2, enc3, enc4
  var i = 0

  while (i < input.length) {
    chr1 = input[i++]
    chr2 = i < input.length ? input[i++] : Number.NaN
    chr3 = i < input.length ? input[i++] : Number.NaN

    enc1 = chr1 >> 2
    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)
    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)
    enc4 = chr3 & 63

    if (isNaN(chr2)) {
      enc3 = enc4 = 64
    } else if (isNaN(chr3)) {
      enc4 = 64
    }
    output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4)
  }
  return output
}

module.exports = {
  base64ToBinary,
  binaryToBase64
}